package io.renren.mqtt;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/updateWm")
@Slf4j
public class UpdateWmHandler {

    //定义session
    private Session session;
//设置焊机数量
    private  int workingCount = 0;
    private  int notWorkingCount = 100;



    private Map<String,Integer> machineStatusMap = new HashMap<>();

    private Set<WebSocketSession> webSocketSessions = new HashSet<>();

    public void setWorkingCount(int workingCount) {
        this.workingCount = workingCount;
    }

    public void setNotWorkingCount(int notWorkingCount) {
        this.notWorkingCount = notWorkingCount;
    }

    public synchronized void addSession(WebSocketSession session) {
        webSocketSessions.add(session);
    }

    public synchronized void removeSession(WebSocketSession session) {
        webSocketSessions.remove(session);
    }

    public synchronized String sendCountToClient() {
        JSONObject countJson = new JSONObject();
        countJson.put("workingCount",workingCount);
        countJson.put("notWorkingCount",notWorkingCount);
//        for(WebSocketSession webSocketSession: webSocketSessions){
//            log.info("广播消息,message={}",countJson);
//            try {
//                webSocketSession.sendMessage(new TextMessage(countJson.toString()));
//            } catch (Exception e){
//                e.printStackTrace();
//            }
//        }
        return countJson.toString();
    }

    synchronized void updateCounts(String wmNo,int status) {
       if(machineStatusMap.containsKey(wmNo)){
           int oldStatus = machineStatusMap.get(wmNo);
           if (oldStatus == 1) {
               workingCount--;
               notWorkingCount++;
           } else {
                notWorkingCount--;
                workingCount++;
           }
       }else{
           if (status == 1) {
               workingCount++;
           } else {
               notWorkingCount--;
           }
       }
       machineStatusMap.put(wmNo,status);
        sendCountToClient();
    }

    //定义一个存储session的容器

    private static CopyOnWriteArraySet<UpdateWmHandler> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void OnOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        log.info("有新连接，总数：" + webSocketSet.size());
    }

    @OnClose
    public void OnClose(){
        webSocketSet.remove(this);
        log.info("连接断开，总数：" + webSocketSet.size());
    }

    @OnMessage
    public void OnMessage(String message,Session session){
        log.info("收到客户端"+session.getId()+"发来的消息：" + message);
        sendMessage("收到消息：" + message);
    }

    public synchronized void sendMessage(String message){
        for(UpdateWmHandler countHandler: webSocketSet){
            log.info("广播消息,message={}",message);
            try {
                countHandler.session.getBasicRemote().sendText(message);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
